import React from 'react';
import { Modal, Transfer } from 'antd';
import styles from './Common.less';

class RelateTransfer extends React.Component {

  constructor() {
    super();
    this.state = {
      targetDatas: [],
      targetKeys: [],
      selectedKeys: [],
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.generateDatas(nextProps);
  }

  generateDatas = (nextProps) => {
    const { correlateType, correlateInfoData, relateList, correlateVos } = nextProps;
    const targetKeys = [];
    const targetDatas = [];
    for (let i = 0; i < relateList.length; i++) {
      const item = relateList[i];
      const fieldName = correlateType == "0" || correlateType == "1" ? "userName" : "name";
      const data = {
        key: item.id,
        title: item[fieldName],
        description: item[fieldName],
        chosen: correlateInfoData && correlateInfoData.userIds ? correlateInfoData.userIds.indexOf(item.id) > -1 : false,
      };
      if (data.chosen) {
        targetKeys.push(data.key);
      }
      targetDatas.push(data);
    }
    let selectedKeys = correlateVos.map(item => item.subjectId);
    this.setState({ targetDatas, targetKeys, selectedKeys });
  };

  filterOption = (inputValue, option) => option.description.indexOf(inputValue) > -1;

  onTargetChange = targetKeys => {
    this.setState({targetKeys});
  };

  onSelectChange = selectedKeys => {
    this.setState({selectedKeys});
  };

  render() {

    const { relateTransferVisible, correlateInfoData, onCancel, addCorrelate, correlateType } = this.props;
    const { targetDatas, targetKeys, selectedKeys } = this.state;

    return (
      <div id={"relateTransfer_" + correlateType}>
        <Modal
          centered={true}
          visible={relateTransferVisible}
          title={(correlateInfoData && correlateInfoData.roleName ? correlateInfoData.roleName + "_" : "") + "分配用户"}
          okText="保存"
          cancelText="取消"
          onCancel={onCancel}
          onOk={() => addCorrelate(targetKeys)}
          width={550}
          destroyOnClose={false}
          bodyStyle={{height: "350px", padding: "18px"}}
        >
          <Transfer
            listStyle={{height: "315px", width: "280px"}}
            titles={["全部用户", "权限用户"]}
            dataSource={targetDatas}
            showSearch
            filterOption={this.filterOption}
            targetKeys={targetKeys}
            selectedKeys={selectedKeys}
            onChange={this.onTargetChange}
            onSelectChange={this.onSelectChange}
            render={item => item.title}
          />
        </Modal>
      </div>
    );
  };
}

export default RelateTransfer;
